package cn.itcast.controller;

import cn.itcast.constant.MessageConstant;
import cn.itcast.entity.Result;
import cn.itcast.pojo.Order;
import cn.itcast.service.OrderService;
import cn.itcast.service.SMSService;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;


@RestController
@RequestMapping("order")
public class OrderController {
    @Reference
    private OrderService orderService;

    @Autowired
    private SMSService smsService;

    /**
     * 参数在map集合里面,获取的时候好获取
     * @param map
     * @return
     */
    @PostMapping("submit")
    public Result submit(@RequestBody Map map) {
        //获取手机号码跟验证码
        String telephone = (String) map.get("phoneNumber");
        String validateCode = (String) map.get("validateCode");
        //如果在redis中查不到数据就说明验证码错误
        boolean checkCode = smsService.checkCode(telephone, validateCode);
        if (!checkCode) {
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }
        //讲数据保存到订单表里面去
        Result result = null;
        try {
            result = orderService.add(map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.ORDER_FAIL);
        }
        System.out.println(result);
        return result;
    }

    @GetMapping("{id}")
    public Result findById(@PathVariable("id") String id) {

        Order order = null;

        if (null == order) {
            return new Result(false,MessageConstant.QUERY_ORDER_FAIL);
        }

        return new Result(true,MessageConstant.QUERY_ORDER_SUCCESS,order);
    }
}
